/**
 * Created by bethinner on 6/6/16.
 */
import React, { Component } from 'react';
import { connect } from 'react-redux'
import Link from 'react-router/lib/Link'
import browserHistory from 'react-router/lib/browserHistory'
import NavigationBar from '../components/NavigationBar'
import EditText from '../components/EditText'
import GreenButton from '../components/GreenButton'
import MessageAlert from '../components/MessageAlert'
import cookie from 'react-cookie'
import {fetchPost,getBack} from '../utils/httpRequest'
export default class LoginContainer extends Component {
    constructor(props) {
        super(props);
        this._onPhoneNumberChange = this.onPhoneNumberChange.bind(this);
        this._onPasswordChange = this.onPasswordChange.bind(this);
        this._handle = this.handle.bind(this);
        this.state = {
            phoneNumber: "",
            password: "",
            returnObj: {},
            showMessage: false
        }
    }

    componentWillMount() {
        //console.log(this.props.location);
        //if(this.props.location.query.retUrl){//登录成功后的跳转url
        //    window.sessionStorage.setItem("retUrl",this.props.location.query.retUrl);
        //}else{
        //    window.sessionStorage.setItem("retUrl","");
        //}
    }

    onPhoneNumberChange(event) {
        this.state.phoneNumber = event.target.value;
    }

    onPasswordChange(event) {
        this.state.password = event.target.value;
    }


    onLogin() {

        var b = /^[\w]{6,20}$/;
        var reg = /^0?1[3|4|5|8][0-9]\d{8}$/;
        if (b.test(this.state.password)) {
            // 调用登录接口,登录成功跳转到首页
            //发送请求
            let param = {user_id: this.state.phoneNumber, password: this.state.password,cap_code:document.getElementById("cap_code").value};
            var url='login';
            $('#loadingToast').show();
            //$.post(document.location.protocol+'//127.0.0.1:8080/city/index.php/home/api/login',param,function(data){
            //    console.log(data);
            //});
            fetchPost(url, param).then(
                response => {
                  return  response.json()
                }
            ).then(
                json => {
                    $('#loadingToast').hide();
                    this.state.returnObj = json;
                    if (this.state.returnObj.code == 0) {
                        //为其他网站登录
                        var retUrl=window.sessionStorage.getItem("retUrl");


                        //if(retUrl&&retUrl.indexOf("http")==0){
                        //    var suffix="?";
                        //    if(retUrl.indexOf("?")>0){
                        //        suffix="&";
                        //    }
                        //    retUrl=retUrl+suffix+"userId="+param.user_id+"&o2osign="+json.data.o2osign;
                        //    location.href=retUrl;
                        //    window.sessionStorage.setItem("retUrl","");
                        //    return ;
                        //}

                        cookie.save('mobile',param.user_id,{path:'/',maxAge:3*24*3600});
                        cookie.save('smid',json.data.smid,{path:'/',maxAge:3*24*3600});
                        cookie.save('o2osign',json.data.o2osign,{path:'/',maxAge:3*24*3600});

                        if(retUrl!=null){
                            browserHistory.replace({
                                pathname: retUrl,
                            });
                            return;
                        }
                        //登录成功
                        if (this.props.location.pathname=='/wepiao'){
                            let param = {mobile: this.state.phoneNumber,o2osign:json.data.o2osign};
                            fetchPost('getWePiaoUrl', param).then(
                                response => {
                                    $('#loadingToast').hide();
                                    return  response.json()
                                }
                            ).then(
                                json => {
                                    if (json.code == 0) {
                                        //获取微票跳转链接成功
                                        location.href=json.data;
                                    } else {
                                        alert("跳转失败，请稍后再试");
                                        //location.href="http://m.wepiao.com";
                                    }
                                }
                            )
                            return ;
                        }
                        var nextPathname ='/index';
                        if (this.props.location.pathname!='/'&&this.props.location.pathname!='/login'){
                             nextPathname =this.props.location.pathname;
                        }

                        if (this.props.location.pathname=='/SubmitOrderContainer'){

                            browserHistory.replace({
                                pathname: '/SubmitOrderContainer',
                                state: {
                                    data: this.props.location.state.data,
                                    card_id: this.props.location.state.card_id
                                }
                            });
                        }else {
                            browserHistory.replace({
                                pathname: nextPathname
                            });
                        }
                    } else {
                        this.setState({showMessage: true});
                    }
                    this.setState({returnObj: json});
                }
            )

        } else {
            alert("帐号密码格式错误")
        }

    }

    //注册state.type传递0
    goRegister() {
        var wePiao =false;
        if (this.props.location.pathname=='/wepiao'){
            wePiao =true;
        }
        browserHistory.push({
                pathname: `/verifyPhone`,
                state: {type: 0,wePiao:wePiao}
            }
        );
    }

    //忘记密码state.type传递1
    forgetPsw() {
        var wePiao =false;
        if (this.props.location.pathname=='/wepiao'){
             wePiao =true;
        }
        browserHistory.push({
                pathname: `/verifyPhone`,
                state: {type: 1,wePiao:wePiao}
            }
        );
    }

    handle(type) {
        var that = this;
        return function () {
            that.setState({showMessage: false});
        }
    }

    getMessageAlert() {
        if (this.state.showMessage == true) {
            return (<MessageAlert message={this.state.returnObj.msg}
                                  type={1}
                                  handle={this._handle}/>)
        } else {
            return ""
        }
    }

    reloadCap(){
        $("#cappic").attr("src",$("#cappic").attr("src"));
    }

    render() {
        return (
            <div style={{background:"white",height:"100%"}}>
            <div style={{background:"white",textAlign:"center",height:"auto",lineHeight:"18px"}}>
                <NavigationBar Title="登录" LeftBar="true"/>
                {this.getMessageAlert()}
                <div style={{backgroundColor:"#E5E5EA",height:"1px"}}></div>
                <img style={{marginTop:"30px",marginBottom:"30px",}} src="/public/img/smk_logo.png"/>
                <div style={{width:"76%",margin: "0 auto 20px" ,textAlign:"left"}}>
                    <EditText imgSrc="/public/img/user.png"
                              placeholder="请输入手机号码"
                              type="number"
                              maxLen={11}
                              onTextChange={this._onPhoneNumberChange}/>
                </div>
                <div style={{width:"76%",margin: "0 auto 20px" ,textAlign:"left"}}>
                    <EditText imgSrc="/public/img/password.png"
                              placeholder="请输入密码"
                              type="password"
                              onTextChange={this._onPasswordChange}/>
                </div>
                <div style={{width:"76%",margin: "0 auto 20px" ,marginTop:"-4px",textAlign:"left"}}>
                         <div>
                            <input id="cap_code" maxLength={"4"} style={{outline:"none",height:"27px",border:"none",width:"58%",fontSize:"14px",marginTop:"9px",float:"left"}} type="text" placeholder="图形验证码"/>
                            <img id="cappic" onClick={this.reloadCap} src={getBack()+"/home/api/getCapImg"} style={{width:'100px',height:'40px'}}/>
                            <div style={{backgroundColor:"#6BAC72",height:"1px"}}>
                            </div>
                             <div style={{textAlign:"right",color:"#9B9B9B", margin:"5px",fontSize:"14px"}} ><span onClick={this.forgetPsw.bind(this)}>忘记密码?</span></div>
                         </div>

                </div>
                <GreenButton onClick={this.onLogin.bind(this)} text="登录"/>
                <div onClick={this.goRegister.bind(this)} style={{fontSize:'14px',color:'#76EE00'}}>
                    注册帐号
                </div>
                <img style={{width:"80%" ,margin: "0"}} src="/public/img/img_line.png"/>
                <div style={{color:'#76EE00' ,fontSize:"12px"}}>
                    在市民卡App或网站注册过的用户可直接使用手机号登录
                </div>
            </div>
            </div>

        )
    }
}

LoginContainer.defaultProps = {}

LoginContainer.propTypes = {}


module.exports = LoginContainer;
